/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kmcsoft.goldshop.jewelryexchange;

import com.kmcsoft.core.ui.GenericController;
import com.kmcsoft.goldshop.generic.service.ShopGenericService;
import com.kmcsoft.goldshop.jewelryexchange.service.JewelryExchangeService;
import com.kmcsoft.goldshop.model.exchange.DiamondExchangeDetail;
import com.kmcsoft.goldshop.model.exchange.JewelryExchange;
import com.kmcsoft.goldshop.model.exchange.JewelryExchangeDetail;
import com.kmcsoft.goldshop.model.master.Currency;
import com.kmcsoft.goldshop.model.master.DiamondColor;
import com.kmcsoft.goldshop.model.master.DiamondGroup;
import com.kmcsoft.goldshop.model.master.PremiumJewelryType;
import com.kmcsoft.util.Utilities;
import com.kmcsoft.utils.i18n;
import com.kmcsoft.zkex.PagingListModel;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Row;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

/**
 *
 * @author huyvu
 */
public class JewelryExchangeComposer extends GenericController<JewelryExchange, JewelryExchangeService> {

    private Grid diamondGrid;
    private Currency currency;
    private JewelryExchange exchange;
    @Autowired
    ShopGenericService shopGenericService;

    //<editor-fold defaultstate="collapsed" desc="doAfterCompose">
    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        currency = shopGenericService.getCurrencyByCode("USD");
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="PagingListModel">
    @Override
    public PagingListModel getListModel() {
        String strFilter = "createdBy.name.matches('(?i).*" + filter.getValue().trim() + ".*')";
        PagingListModel<JewelryExchange> model = Utilities.getPagingListModel(objectClass, HashMap.class, "id,createdBy.name,createdDate", strFilter);
        model.setOrdering("createdDate descending");
        model.initialize();
        return model;
    }

    public void setSelected(HashMap selected) {
        super.setSelected(service.getJewelryExchangeById(selected.get("id")));
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onCreate">
    public void onCreate() {
        onClick$new(null);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="doAfterNew">
    @Override
    protected void doAfterNew() {
        super.doAfterNew();

        if (getListModel().getSize() != 0) {
            exchange = service.getJewelryExchangeById(((HashMap) getListModel().getElementAt(0)).get("id"));
            for (DiamondExchangeDetail detail : exchange.getDiamondDetails()) {
                selected.getDiamondDetails().add(new DiamondExchangeDetail(detail));
            }
        }
        Collection<PremiumJewelryType> jewelryTypes = service.getJewelryTypes();
        for (PremiumJewelryType jewelryType : jewelryTypes) {
            selected.getJewelryDetails().add(new JewelryExchangeDetail(jewelryType));
        }
        selected.setUse(true);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="doBeforeSave">
    @Override
    protected void doBeforeSave() {
        super.doBeforeSave();
        checkBeforeSave();
        for (JewelryExchangeDetail detail : selected.getJewelryDetails()) {
            detail.getJewelryType().setUnitPrice(detail.getSellingPrice());
        }
        if (exchange != null) {
            exchange.setUse(false);
            service.makePersistent(exchange);
        }
    }
    //</editor-fold>

    @Override
    protected void doAfterSave() {
        super.doAfterSave();
        super.setSelected(service.getJewelryExchangeById(selected.getId()));
    }

    //<editor-fold defaultstate="collapsed" desc="GET/SET">
    public Collection<DiamondGroup> getGroups() {
        return service.getGroups();
    }

    public Collection<DiamondColor> getColors() {
        return service.getColors();
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onAddDiamondGroup">
    public void onAddDiamondGroup(ForwardEvent event) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("binder", getBinder());
            map.put("component", diamondGrid);
            Window win = (Window) Executions.createComponents("/shop/modal/diamondGroupModal.zul", null, map);
            win.doModal();
        } catch (Exception ex) {
            log.error("ERROR from onAddDiamondGroup", ex);
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onAddDiamondColor">
    public void onAddDiamondColor(ForwardEvent event) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("binder", getBinder());
            map.put("component", diamondGrid);
            Window win = (Window) Executions.createComponents("/shop/modal/diamondColorModal.zul", null, map);
            win.doModal();
        } catch (Exception ex) {
            log.error("ERROR from onAddDiamondGroup", ex);
        }
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onInsertRow">
    public void onInsertRow(ForwardEvent event) {
        Grid grid = (Grid) event.getOrigin().getTarget().getParent().getParent().getParent();
        selected.getDiamondDetails().add(new DiamondExchangeDetail(currency));
        getBinder().loadComponent(grid);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="onRemove">
    public void onRemove(ForwardEvent event) {
        Grid grid = (Grid) event.getOrigin().getTarget().getParent().getParent().getParent();
        if (grid.getModel().getSize() == 1) {
            return;
        }
        Toolbarbutton btton = (Toolbarbutton) event.getOrigin().getTarget();
        Row row = ((Row) btton.getParent());
        Object selectedRecord = row.getValue();
        ((BindingListModelList) grid.getModel()).remove(selectedRecord);
        grid.renderAll();
    }
    //</editor-fold> 

    //<editor-fold defaultstate="collapsed" desc="checkBeforeSave">
    private void checkBeforeSave() {
        for (DiamondExchangeDetail detail : selected.getDiamondDetails()) {
            DiamondColor color = detail.getDiamondColor();
            DiamondGroup group = detail.getDiamondGroup();
            boolean check = false;
            for (DiamondExchangeDetail de : selected.getDiamondDetails()) {
                if (de.getDiamondColor().equals(color) && de.getDiamondGroup().equals(group)) {
                    if (check) {
                        throw new WrongValueException(i18n.l("shop.jewelryRate.diamond.error"));
                    }
                    check = true;
                }
            }
        }
    }
    //</editor-fold>
}
